package com.woniuxy.service.impl;

import com.woniuxy.entity.Menu;
import com.woniuxy.mapper.MenuMapper;
import com.woniuxy.service.MenuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class MenuServiceImpl implements MenuService {
    private  MenuMapper menuMapper;

    /**
     * 查询用户菜单
     * 把数据转化为一级菜单中包含二级菜单的结构
     * 1.先找出所有的父菜单
     * 2.循环父菜单，去菜单的集合里找出所有的子菜单
     * 3.把子菜单放到父菜单中
     * @param userId
     * @return
     */
    @Override
    public List<Menu> queryUserMenu(Integer userId) {
        List<Menu> menus = menuMapper.queryUserMenu(userId);
        List<Menu> parentMenu = menus.stream().filter(menu -> menu.getParentId() == -1)
                .collect(Collectors.toList());

        for (Menu pMenu : parentMenu) {
            List<Menu> childrenMenu = new ArrayList<>();
            for (Menu menu : menus) {
                if(pMenu.getId().equals(menu.getParentId())){
                    childrenMenu.add(menu);
                }
            }
            pMenu.setChildrenMenu(childrenMenu);
        }

        return parentMenu;
    }
}
